package com.niiwoo.civet.user.service.local.notify;

import java.util.List;
import java.util.stream.Collectors;

import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.niiwoo.civet.account.dto.request.GetUnOnpenBankAccountRequestDTO;
import com.niiwoo.civet.account.service.notify.PersonalizedNotifyAccountDubboService;
import com.niiwoo.civet.user.dao.entity.UserBasicInfo;
import com.niiwoo.civet.user.dao.mapper.UserBasicInfoMapperExt;
import com.niiwoo.civet.user.dto.request.UserLetterRequestDTO;
import com.niiwoo.civet.user.enums.MessageTemplateKeyEnum.JPushTemplateKeyEnum;
import com.niiwoo.civet.user.enums.MessageTemplateKeyEnum.LetterTemplateKeyEnum;
import com.niiwoo.civet.user.enums.SMSTemplateKeyEnum;
import com.niiwoo.civet.user.enums.UserLetterTypeEnum;
import com.niiwoo.civet.user.service.SendSmsDubboService;
import com.niiwoo.civet.user.service.UserLetterDubboService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class PersonalizedNotifyUserLocalService {
	
	@Autowired
	public UserLetterDubboService userLetterDubboService;

	@Autowired
	public SendSmsDubboService sendSmsDubboService;
	
	@Autowired
	private UserBasicInfoMapperExt userBasicInfoMapperExt;
	
	@Reference(version = "1.0.0")
	private PersonalizedNotifyAccountDubboService personalizedNotifyAccountDubboService;
	
	/**
	 * 用户注册后未开通银行存管帐户
	 */
	public void unopenInvestmentAccount() {
		Long beginTime = System.currentTimeMillis();
		log.info("###个性化通知-用户注册未开通存管帐户###推送信息任务开始");
		List<UserBasicInfo> userBasicInfoList = userBasicInfoMapperExt.selectRegisterTimeForAssignDays(3);
		if (CollectionUtils.isEmpty(userBasicInfoList)) {
			log.info("###个性化通知-用户注册未开通存管帐户###当前没有符合条件的注册用户，推送信息任务结束，总耗时：{}ms", System.currentTimeMillis() - beginTime);
			return;
		}
		
		// 调用帐户中心查询未开通存管帐户(借款、投资)
		List<String> userIdListForAccount = userBasicInfoList.stream().map(UserBasicInfo::getUserId).collect(Collectors.toList());
		GetUnOnpenBankAccountRequestDTO requestDTO = new GetUnOnpenBankAccountRequestDTO();
		requestDTO.setUserIdList(userIdListForAccount);
		List<String> userIdList = personalizedNotifyAccountDubboService.getUnOnpenBankAccount(requestDTO);
		if (CollectionUtils.isEmpty(userIdList)) {
			log.info("###个性化通知-用户注册未开通存管帐户###当前没有符合条件的存管帐户，推送信息任务结束，总耗时：{}ms", System.currentTimeMillis() - beginTime);
			return;			
		}
		log.info("###个性化通知-用户注册未开通存管帐户###当前需要推送信息的总用户数：{}", userIdList.size());

		// 构建消息参数（所有用户推送的消息参数是一致）
		List<Object> paramMap = Lists.newArrayList();
		log.info("###个性化通知-用户注册未开通存管帐户###信息参数：{}", JSONObject.toJSONString(paramMap));
		
		// 个性化通知-用户注册未开通存管帐户
		userIdList.parallelStream().forEach(userId -> {
			pushUnopenInvestmentAccountMessageToUser(userId, paramMap);
		});
		log.info("###个性化通知-用户注册未开通存管帐户###推送信息任务结束，总耗时：{}ms", System.currentTimeMillis() - beginTime);
	}
	
	public void pushUnopenInvestmentAccountMessageToUser(String userId, List<Object> paramMap) {
		log.info("###个性化通知-用户拥有即将过期的红包###推送信息，UserId:{}", userId);
		try {
			// 查询用户信息
			UserBasicInfo userBasicInfo = userBasicInfoMapperExt.selectByPrimaryKey(userId);
			
			// 站内信和极光推送
			UserLetterRequestDTO userLetterRequestDTO = new UserLetterRequestDTO();
			userLetterRequestDTO.setToUserId(userId);
			userLetterRequestDTO.setUserLetterTypeEnum(UserLetterTypeEnum.LETTER_AND_JPUSH);
			userLetterRequestDTO.setJpushTemplateKeyEnum(JPushTemplateKeyEnum.PERSONALIZED_NOTIFY_UNOPEN_INVEST_ACCOUNT);
			userLetterRequestDTO.setJpushTemplateParamList(paramMap);
			userLetterRequestDTO.setLetterTemplateEnum(LetterTemplateKeyEnum.PERSONALIZED_NOTIFY_UNOPEN_INVEST_ACCOUNT);
			userLetterRequestDTO.setLetterTemplateParamList(paramMap);
			userLetterDubboService.pushLetter(userLetterRequestDTO);
			
			// 发送短信
			sendSmsDubboService.sendSmsByMobile(userBasicInfo.getMobileNo(),
					SMSTemplateKeyEnum.PERSONALIZED_NOTIFY_UNOPEN_INVEST_ACCOUNT.getKey(), paramMap);
		} catch (Exception e) {
			log.error("###个性化通知-用户拥有即将过期的红包###推送信息异常，UserId:{}", userId, e);
		}
		log.info("###个性化通知-用户拥有即将过期的红包###推送信息结束，UserId:{}", userId);
	}

	/**
	 * 注册成功消息推送
	 * 
	 * @param userId
	 */
	public void pushRegisterSuccessMessageToUser(String userId) {
		log.info("###个性化通知-注册成功###推送信息，UserId:{}", userId);
		try {
			UserBasicInfo userBasicInfo = userBasicInfoMapperExt.selectByPrimaryKey(userId);
			// 内容参数
			List<Object> paramMap = Lists.newArrayList();
			
			// 站内信和极光推送
			UserLetterRequestDTO userLetterRequestDTO = new UserLetterRequestDTO();
			userLetterRequestDTO.setToUserId(userBasicInfo.getUserId());
			userLetterRequestDTO.setUserLetterTypeEnum(UserLetterTypeEnum.LETTER_AND_JPUSH);
			userLetterRequestDTO.setJpushTemplateKeyEnum(JPushTemplateKeyEnum.PERSONALIZED_NOTIFY_REGISTER_SUCCESS);
			userLetterRequestDTO.setJpushTemplateParamList(paramMap);
			userLetterRequestDTO.setLetterTemplateEnum(LetterTemplateKeyEnum.PERSONALIZED_NOTIFY_REGISTER_SUCCESS);
			userLetterRequestDTO.setLetterTemplateParamList(paramMap);
			userLetterDubboService.pushLetter(userLetterRequestDTO);
			
			// 发送短信
			sendSmsDubboService.sendSmsByMobile(userBasicInfo.getMobileNo(),
					SMSTemplateKeyEnum.PERSONALIZED_NOTIFY_REGISTER_SUCCESS.getKey(), paramMap);
		} catch (Exception e) {
			log.error("###个性化通知-注册成功###推送信息异常，UserId:{}", userId, e);
		}
		log.info("###个性化通知-注册成功###推送信息结束，UserId:{}", userId);
	}
}